import React, { useState, useContext } from 'react';
import { NavBar, List, TextArea, Form, ActionSheet, Toast } from "antd-mobile";
import { useHistory } from 'react-router-dom';

import SelectBatchSendContactor from '../../../components/SelectBatchSendContactor';

import { MySdkStoreContext } from '../../../context';
import { ConversationType } from '../../../constants';

import './style.scss';

export default function() {
  const history = useHistory();
  const mySdkStore = useContext(MySdkStoreContext);
  const [form] = Form.useForm();
  // 已选择的会话Id
  const [selectedCids, setSelectedCids] = useState([]);
  // 已选择的用户id
  const [selectedUids, setSelectedUids] = useState([]);
  // "选择用户/会话"弹窗界面Props
  const [selectBatchSendContactorProps, setSelectBatchSendContactorProps] = useState({ visible: false });
  // "选择群发方式"菜单是否展示开关
  const [selectorTypeVisible, setSelectorTypeVisible] = useState(false);
  // 群发方式
  const [batchType, setBatchType] = useState(ConversationType.Notify);
  // “选择群发对象”错误验证
  const [selectContractorError, setSelectContractorError] = useState('');

  // 点击“发送”事件
  const handleSend = () => {
    form.validateFields().then(async (values) => {
      try {
        if ((ConversationType.Notify === batchType && !selectedCids.length) || (ConversationType.Single === batchType && !selectedUids.length)) {
          setSelectContractorError('请选择群发对象');
          return;
        } else {
          setSelectContractorError('');
        }
        const msg = mySdkStore.sdk.messageBuilder({
            msgType: 'text',
            msgContent: { value: values.text },
            toCids: ConversationType.Notify === batchType ? selectedCids.map(({ value }) => value) : [],
            toUserIds: ConversationType.Single === batchType ? selectedUids.map(({ value }) => value) : [],
            sendToUserBySingle: batchType === ConversationType.Single
        });

        const { sendOk } = await mySdkStore.sdk.sendMessageByBatch(msg);
        if (sendOk) {
          Toast.show('消息群发成功，正在返回...');
          setTimeout(history.goBack, 1500);
        }
      } catch(e: any) {
        Toast.show(e.errorMessage);
      }
    });
  }

  // 点击”群发对象“事件，展示”选择对象“界面
  const handleSelectContractor = () => {
    setSelectBatchSendContactorProps({
      visible: true,
      title: '选择对象',
      batchType,
      onOk: async (ids, allInfoItems) => {
        // 根据群发类型，填充相关数据：群发类型为”工作通知“，填充为”会话id(cid)“；群发类型为”单聊通知“，填充为”用户id（uid）“
        batchType === ConversationType.Notify ? setSelectedCids(allInfoItems) : setSelectedUids(allInfoItems);
        ids.length && setSelectContractorError('');
        setSelectBatchSendContactorProps({ visible: false });
      },
      onClose: () => setSelectBatchSendContactorProps({ visible: false})
    });
  }

  // 点击”群发类型“事件，展示”群发菜单“界面
  const handleSelectType = () => {
    setSelectorTypeVisible(true);
  }

  // ”选择群发方式“， ActionSheet->actions
  const actions = [
    { text: '工作通知', key: ConversationType.Notify },
    { text: '单聊通知', key: ConversationType.Single },
  ];

  // 选择对象完成后，展示选择结果，渲染会话名称或用户名称
  const renderSelectedName = () => {
    if (batchType === ConversationType.Notify) {
      return selectedCids.length ? selectedCids.map(item => item.label).join('，') : '未选择';
    } else {
      return selectedUids.length ? selectedUids.map(item => item.label).join('，')  : '未选择';
    }
  }

  // 改变”群发类型“事件处理
  const handleChangeSelectorType = (action) => {
    setBatchType(action.key);
    setSelectorTypeVisible(false);
  }

  return (
    <div className="sendMessageByBatchPage">
      <NavBar
        onBack={() => history.goBack()} style={{ background: '#fff', border: 'none' }}
        right={<a onClick={handleSend} style={{ fontSize: 17 }}>发送</a>}
      >群发消息</NavBar>
      <Form
        form={form}
        style={{ margin: '12px 0' }}>
        <Form.Item
          label={null}
          name="text"
          rules={[{ required: true, message: '请输入群发内容' }]}
          >
            <TextArea
              placeholder='请输入群发内容'
              rows={5}
              maxlength={500}
            />
          </Form.Item>
      </Form>
      <List style={{ '--border-top': 0, '--border-bottom': 0 }}>
        <List.Item extra={ConversationType.Single === batchType ? '单聊通知' : '工作通知'} onClick={handleSelectType}>
          群发方式
        </List.Item>
        <List.Item extra={renderSelectedName()} onClick={handleSelectContractor}>
          群发对象
          {selectContractorError && <div className="selectContractorError">
            { selectContractorError }
          </div> }
        </List.Item>
      </List>
    { selectBatchSendContactorProps.visible && <SelectBatchSendContactor {...selectBatchSendContactorProps} /> }
    <ActionSheet
      extra='选择群发方式'
      cancelText='取消'
      visible={selectorTypeVisible}
      actions={actions}
      onClose={() => setSelectorTypeVisible(false)}
      onAction={handleChangeSelectorType}
    />
    </div>
  )
}